﻿using System;
using System.Windows.Forms;
using System.Data;
using Gencode.PrsCommon.Data.Dienst;
using Gencode.Gengui;

namespace Gencode.PrsUtil.Controls
{
	public class PUDienstZeitenGrid : DataGridView
	{
		DataView m_zeiten;
		private System.Windows.Forms.DataGridViewTextBoxColumn von;
		private System.Windows.Forms.DataGridViewTextBoxColumn bis;
		private System.Windows.Forms.DataGridViewTextBoxColumn typ;

		public PUDienstZeitenGrid()
			: base()
		{
			InitializeLayout();
		}

		protected override void Dispose(bool disposing)
		{
			if (m_zeiten != null)
				m_zeiten.Dispose();

			base.Dispose(disposing);
		}

		protected override void OnDataBindingComplete(DataGridViewBindingCompleteEventArgs e)
		{
			base.OnDataBindingComplete(e);
		}

		protected override void InitLayout()
		{
			base.InitLayout();
			this.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
		}

		protected void InitializeLayout()
		{
			if (Columns.Count > 0)
				Columns.Clear();

			this.von = new DataGridViewTextBoxColumn();
			this.bis = new DataGridViewTextBoxColumn();
			this.typ = new DataGridViewTextBoxColumn();
			((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
			this.SuspendLayout();
			this.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
				this.typ,
				this.von,
				this.bis});

			this.typ.HeaderText = "Typ";
			this.typ.Name = "typ";
			this.typ.ReadOnly = true;

			this.von.HeaderText = "Von";
			this.von.Name = "von";
			this.von.ReadOnly = true;

			this.bis.HeaderText = "Bis";
			this.bis.Name = "bis";
			this.bis.ReadOnly = true;
			this.bis.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

			((System.ComponentModel.ISupportInitialize)(this)).EndInit();
			this.ResumeLayout(false);
		}

		public void ReloadData(int dienstid)
		{
			if (m_zeiten != null)
				m_zeiten.Dispose();

			m_zeiten = DienstData.GetDienstZeiten(dienstid);
			BindData();
		}

		private void BindData()
		{
			AutoGenerateColumns = false;
			DataSource = m_zeiten;

			Columns["typ"].DataPropertyName = "typ";
			Columns["von"].DataPropertyName = "von";
			Columns["bis"].DataPropertyName = "bis";
		}

		public void DelteSelectedZeit()
		{
			int index = 0;
			try
			{
				index = SelectedRows[0].Index;
			}
			catch { }

			if (index > 0)
			{
				DienstData.DeleteDienstZeit(int.Parse(m_zeiten[index].Row["dienstzeitid"].ToString()));
				ReloadData(int.Parse(m_zeiten[index].Row["dienstid"].ToString()));
			}
		}
	}
}
